'''
Created on Dec 12, 2009

@author:     Juan Catalano - Alberto Pose
@warning:    This module is subject to goear's modifications in the
             the way they implement the service.
'''

import re
from urllib import urlopen, urlencode
from metadatafetcher import MetaDataFetcher

DS = '/'

class GoearConsumer(object):

    
    def __init__(self, goear_url='http://www.goear.com',xml_meta_url=None, 
                 search_url='http://77.67.11.180/reqsearch.php?'):
        '''
        Constructor
        '''
        self.goear_url = goear_url
        self.search_url = search_url
        
        if xml_meta_url is None:
            self.xml_meta_url = DS.join([self.goear_url, 'files', 'xmlfiles', \
                                    '%s', 'secm%s.xml'])
        
    def search_songs(self, query, page):
        ''' Search for the required song and returns
        the ids provided by goear. Those ids must 
        then be used to access to the xml files that
        describes the mp3 file.
        '''
        
        ans = []
        if query is None:
            return ans
        
        url_hndlr = urlopen(self.search_url + urlencode({'q':query, 'p':page}))
        c =''.join(url_hndlr.readlines())
        ret = [c[i.start() + len('listen/'): i.end()-1]
            for i in re.finditer('listen/([0-9a-zA-Z]+)/', c)]
            
        xmls = []
        
        if ret != []:
            
            fetchlist = []
    
            for res in ret:
                current = MetaDataFetcher( self.xml_meta_url % (res[0], res), xmls )
                fetchlist.append(current)
                current.start()
    
            for fetch in fetchlist:
                fetch.join()
    
        else:
            return []

        return xmls
                    
        
        